<?php

add_filter('query_vars', 'omeka_addons_queryvars' );

function omeka_addons_queryvars( $qvars )
{
  $qvars[] = 'addons';
  return $qvars;
}

add_filter('template_redirect','omeka_addons_templates');

function omeka_addons_templates() {
    global $wp_query;
    $addons = $wp_query->query_vars['addons']; 
    if(!empty($addons)) {
        include(OMEKA_ADDONS_PATH.'template.php');
        exit;
    }
}

add_action('init', 'omeka_addons_flush_rewrite_rules');

function omeka_addons_flush_rewrite_rules() 
{
   global $wp_rewrite;
   $wp_rewrite->flush_rules();
}

add_action('generate_rewrite_rules', 'omeka_addons_add_rewrite_rules');

function omeka_addons_add_rewrite_rules( $wp_rewrite ) 
{
    $new_rules = array(
        OMEKA_ADDONS_BASE_URL.'/(.+)/tag/(.+)' => 'index.php?addons='.$wp_rewrite->preg_index(1).'&tag='.$wp_rewrite->preg_index(2),
        OMEKA_ADDONS_BASE_URL.'/(.+)' => 'index.php?addons='.$wp_rewrite->preg_index(1),
        OMEKA_ADDONS_BASE_URL => 'index.php?addons=home'
    );
    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}